// Fill out your copyright notice in the Description page of Project Settings.


#include "MovablePlatformBaseCpp.h"
#include "PlayerBaseCpp.h"

// Sets default values
AMovablePlatformBaseCpp::AMovablePlatformBaseCpp()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	BoxCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("Box Collider"));
	BoxCollider->SetSimulatePhysics(false);
	BoxCollider->SetEnableGravity(false);
	BoxCollider->SetGenerateOverlapEvents(false);
	RootComponent = BoxCollider;

	SpriteComponent = CreateDefaultSubobject<UPaperFlipbookComponent>(TEXT("Sprite Component"));
	SpriteComponent->SetupAttachment(RootComponent);

	DeathCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("Death Collider"));
	DeathCollider->SetEnableGravity(false);
	DeathCollider->SetSimulatePhysics(false);
	DeathCollider->SetGenerateOverlapEvents(true);
	DeathCollider->SetupAttachment(RootComponent);
	Tags.Add(FName("Platform"));
}

// Called when the game starts or when spawned
void AMovablePlatformBaseCpp::BeginPlay()
{
	Super::BeginPlay();
	FScriptDelegate OverlapDelegate;
	OverlapDelegate.BindUFunction(this, "OnPlayerOverlapStart");
	DeathCollider->OnComponentBeginOverlap.Add(OverlapDelegate);
}

// Called every frame
void AMovablePlatformBaseCpp::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	const FVector CurrentLocation = GetActorLocation();
	if (MoveDirection.Z == 0.0f)
	{
		const float NextLocation = CurrentLocation.X + MoveDirection.X * MoveSpeed * DeltaTime;
		if (NextLocation < Border.X || NextLocation > Border.Y)
		{
			MoveDirection = -MoveDirection;
		}
		SetActorLocation(CurrentLocation + MoveDirection * MoveSpeed * DeltaTime);
	}
	else if (MoveDirection.X == 0.0f)
	{
		const float NextLocation = CurrentLocation.Z + MoveDirection.Z * MoveSpeed * DeltaTime;
		if (NextLocation < Border.X || NextLocation > Border.Y)
		{
			MoveDirection = -MoveDirection;
		}
		SetActorLocation(CurrentLocation + MoveDirection * MoveSpeed * DeltaTime);
	}
}

void AMovablePlatformBaseCpp::OnPlayerOverlapStart(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (OtherActor && OtherActor->ActorHasTag(FName("Player")))
	{
		UE_LOG(LogTemp, Warning, TEXT("Overlap"));
		APlayerBaseCpp* CurrentPlayer = Cast<APlayerBaseCpp>(OtherActor);
		UGameplayStatics::ApplyDamage(CurrentPlayer, 1000.0f, nullptr, this, nullptr);
	}
}

